import datetime
import os.path

from django.db import models
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.utils.translation import ugettext as _
from django.conf import settings

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

try:
    from PIL import Image
except ImportError:
    import Image

from avatar import AVATAR_STORAGE_DIR, AVATAR_RESIZE_METHOD

def avatar_file_path(instance=None, user=None):
    user = user or instance.user
    filename = str(user.id)+'.jpg'
    return os.path.join(AVATAR_STORAGE_DIR, filename)

class Avatar(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(max_length=1024, upload_to=avatar_file_path, blank=True)
    date_uploaded = models.DateTimeField(default=datetime.datetime.now)
    
    def __unicode__(self):
        return _(u'Avatar for %s') % self.user
       
    def thumbnail_exists(self):
        return self.avatar.storage.exists(self.avatar_name())
    
    def create_thumbnail(self, size):
        try:
            orig = self.avatar.storage.open(self.avatar.name, 'rb').read()
            image = Image.open(StringIO(orig))
        except IOError:
            return # What should we do here?  Render a "sorry, didn't work" img?
        (w, h) = image.size
        if w != size or h != size:
            if w > h:
                diff = (w - h) / 2
                image = image.crop((diff, 0, w - diff, h))
            else:
                diff = (h - w) / 2
                image = image.crop((0, diff, w, h - diff))
            image = image.resize((size, size), AVATAR_RESIZE_METHOD)
            if image.mode != "RGB":
                image = image.convert("RGB")
            thumb = StringIO()
            image.save(thumb, "JPEG")
            thumb_file = ContentFile(thumb.getvalue())
        else:
            thumb_file = ContentFile(orig)
        
        if default_storage.exists(self.avatar_name()):
            print("delete")
            default_storage.delete(self.avatar_name())

        thumb = self.avatar.storage.save(self.avatar_name(), thumb_file)
 
    def create_thumbnail_pos(self, size, pos): # width > x2 > x1 and height > y2 > y1
        
        try:
            orig = self.avatar.storage.open(self.avatar.name, 'rb').read()
            image = Image.open(StringIO(orig))
        except IOError:
            return # What should we do here?  Render a "sorry, didn't work" img?
        (w, h) = image.size
 
        if len(pos) != 4:   # wrong parameter pos[0] = x1 pos[1] = x2 pos[2] = x2 pos[3] = y2
            return

        if pos[2] > w or pos[3] > h:    # wrong imput paramter
            return create_thumbnail(AVATAR, (pos[2]-pos[0]))
        print(pos, size)
        
        image = image.crop((pos[0], pos[1], pos[2], pos[3]))
        image = image.resize((size, size), AVATAR_RESIZE_METHOD)
        if image.mode != "RGB":
            image = image.convert("RGB")
        thumb = StringIO()
        image.save(thumb, "JPEG")
        thumb_file = ContentFile(thumb.getvalue())

        if default_storage.exists(self.avatar_name()):
            print("delete")
            default_storage.delete(self.avatar_name())        
        thumb = self.avatar.storage.save(self.avatar_name(), thumb_file)

    def avatar_orig_url(self):
        img = str(self.user.id)+'.jpg'
        name = os.path.join(AVATAR_STORAGE_DIR, img)
        return self.avatar.storage.url(name)
 
    def avatar_url(self):
        return self.avatar.storage.url(self.avatar_name())

    def avatar_name(self):
        filename=str(self.user.id)+'.min.jpg'
        return os.path.join(AVATAR_STORAGE_DIR, filename)

    def avatar_orig_size(self): 
        try:
            orig = self.avatar.storage.open(self.avatar.name, 'rb').read()
            image = Image.open(StringIO(orig))
        except IOError:
            return # What should we do here?  Render a "sorry, didn't work" img?
        return image.size

    def save(self, force_insert=False, force_update=False):
        try:
            old_obj = Avatar.objects.get(pk=self.pk)
            if old_obj.avatar.path != self.avatar.path:
                    path = old_obj.avatar.path
                    default_storage.delete(path)
        except:
            pass
        super(Avatar, self).save(force_insert, force_update)
    
